#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <math.h>
#include <limits.h>
#include <assert.h>

int main(int argc, char* argv[]) {

    // 基本参数
    char *filename_vector = argv[1];
    char *filename_vector_cleaned = argv[2];
    int n = atoi(argv[3]);        
    int kind = atoi(argv[4]); // 0: init, 1: rhs
    assert(kind == 0 || kind == 1);
    printf("[Reading vector from %s]\n", filename_vector);

    // 读取向量的临时变量
    double *vec = new double[n];

    // 开始读取
    FILE *fp = fopen(filename_vector, "r");  
    fscanf(fp, "Vec_s = [\n");   
    double ck_sum = 0.0;
    if (kind == 0) {
        for(int i = 0; i < n; i++)
        {
            int t0; double t1, t2, t3;
            fscanf(fp, "%d %lf %lf %lf %lf", &t0, &vec[i], &t1, &t2, &t3);
            ck_sum += vec[i];
        }
    } else {
        for(int i = 0; i < n; i++)
        {
            fscanf(fp, "%lf", &vec[i]);
            ck_sum += vec[i];
        }
    }
    
    fclose(fp);

    printf("[Vector load finish]\n");
    printf("[check sum = %.8f]\n", ck_sum);
    printf(" ===> writing to binaries....\n");

    // 写入二进制文件
    char target[200];
    int size;

    if (kind == 0)
        sprintf(target, "%s/x0.bin\0", filename_vector_cleaned);
    else
        sprintf(target, "%s/b.bin\0", filename_vector_cleaned);
    fp = fopen(target, "wb+");
    size = fwrite(vec, sizeof(double), n, fp);
    printf("write %d into vector at [%s]\n", size, target);
    fclose(fp);

    printf("\n");

    return 0;
}

